package com.gyh.system.sys.web;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.gyh.system.common.persistence.BaseController;
import com.gyh.system.common.utils.Global;
import com.gyh.system.common.utils.R;
import com.gyh.system.sys.entity.LoginUser;
import com.gyh.system.sys.entity.User;
import com.gyh.system.sys.service.ShiroService;
import com.gyh.system.sys.service.SystemService;

/**
* @author 作者 gyh:
* @version 创建时间：2018年1月13日 上午12:58:03
* 
*/
@RestController
@CrossOrigin
public class LoginController extends BaseController{
	@Autowired
	private SystemService systemService;
	
	@Autowired
	private ShiroService shiroService;
	
	@PostMapping("/login")
	public R login(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
		String userName = request.getParameter("userName");
		log.info(userName+"用户，正在登入操作。。。。。。。。。");
		String password = request.getParameter("password");
		Subject subject = SecurityUtils.getSubject();
		UsernamePasswordToken token = new UsernamePasswordToken(userName, password);
		try {
			subject.login(token);
			Session session = subject.getSession();
			session.setAttribute("userName", userName);
			return R.url("view/system/main.jsp");
		} catch (Exception e) {
			log.info("登入失败！！！！！！！！");
			return R.error("/login.jsp", "用户名或者密码错误");
		}
	}
	
	
	@RequestMapping("/logout")
	public String logout() {
		Subject subject = null;
		try {
			subject = SecurityUtils.getSubject();
		}finally {
			subject.logout();
		}
		return "redirect:/login.jsp";
	}
	
	/**
	 * 登录
	 */
	@PostMapping(value = "/logins")
	public R login(@RequestBody LoginUser loginUser)throws IOException {
		String password = loginUser.getPassword();
		String username = loginUser.getUsername();
		//用户信息
		User user = systemService.getUserByLoginName(username);

		System.out.println("点击登入按钮");
		
		//账号不存在、密码错误
		if(user == null || !SystemService.validatePassword(password, user.getPassword())){
			return R.error("账号或密码不正确");
		}
		
		return shiroService.createToken(user.getId());
	}
	
	
	
}
